const router = require('./routers/index.js');

const express = require('express');
const path = require('path');
const fs = require('fs');
const util = require('util');
const pkg = require('../package.json');
// var execa = require('execa');
const chalk = require('chalk');
const os = require('os');
var compression = require('compression');

const WEEK = 7 * 24 * 60 * 60 * 1000;

const readFile = util.promisify(fs.readFile); // 文件读取改为promise方式

const PORT = process.env.PORT || 3000;

const start = async () => {
  // await execa('npm', ['run', 'build'], { stdio: 'inherit' })

  const index = readFile(resolveFromRoot('dist', 'index.html'), { encoding: 'utf8' });

  const app = express();

  app.use(compression());
  app.use(express.static(path.join(__dirname, resolveFromRoot('dist'))));

  app.all('*', (req, res, next) => {
    const { origin, Origin, referer, Referer } = req.headers;
    const allowOrigin = origin || Origin || referer || Referer || '*';
    res.header('Access-Control-Allow-Origin', allowOrigin);
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('X-Powered-By', 'Express');
    // res.header('content-encoding', 'gzip,deflate');
    // content-encoding: gzip
    if (req.method === 'OPTIONS') {
      res.sendStatus(200);
    } else {
      next();
    }
  });

  app.use('/', serve('dist')); // 提供静态资源文件

  router(app); // 应用路由

  app.get('*', indexHandler); // 返回前端页面

  const ipAddress = getIpAddress();

  app.listen(PORT, () => {
    console.log(`${pkg.name} is up and running on port ${PORT}!`);
    console.log(chalk.green(`http://${ipAddress}:${PORT}`));
    console.log(chalk.green(`http://localhost:${PORT}`));
  });

  function indexHandler(req, res) {
    res.set('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.set('Expires', '-1');
    index.then(html => {
      res.send(html);
    });
  }
};

/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
  var ifaces = os.networkInterfaces();

  for (var dev in ifaces) {
    let iface = ifaces[dev];

    for (let i = 0; i < iface.length; i++) {
      let { family, address, internal } = iface[i];

      if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
        return address;
      }
    }
  }
}

function serve(staticPath) {
  return express.static(resolveFromRoot(staticPath), {
    maxAge: null,
  });
}

function resolveFromRoot(...relativePath) {
  return path.resolve(__dirname, '..', ...relativePath);
}

start();
